package com.stoneframe.plugin.websocketInstantMsg;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Date;

import org.codehaus.jettison.json.JSONObject;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;


/**
 * 即时通讯
 */
public class ChatServer extends WebSocketServer {
	
	public ChatServer(int port) throws UnknownHostException{
		super(new InetSocketAddress(port));
	}
	
	public ChatServer(InetSocketAddress address){
		super(address);
	}

	@Override
	public void onClose(WebSocket conn, int code, String reason, boolean remote) {
		// TODO Auto-generated method stub
		System.out.println("即时通讯===触发关闭事件===" + conn.getRemoteSocketAddress().getAddress().getHostAddress());
		userLeave(conn);
	}

	@Override
	public void onError(WebSocket conn, Exception e) {
		// TODO Auto-generated method stub
		System.out.println("即时通讯===触发异常事件===" + conn.getRemoteSocketAddress().getAddress().getHostAddress());
		System.out.println("即时通讯===触发异常事件===" + e.getCause().toString());
	}

	@Override
	public void onMessage(WebSocket conn, String message) {
		// TODO Auto-generated method stub
		System.out.println("即时通讯===客户端发送消息到服务器时触发事件===" + conn.getRemoteSocketAddress().getAddress().getHostAddress()+message);
		message = message.toString();
		if(null != message && message.startsWith("StoneFrame")){
			this.userJoin(message.replaceFirst("StoneFrame", ""),conn);
		}if(null != message && message.startsWith("StoneFrameLeave")){
			this.userLeave(conn);
		}if(null != message && message.contains("StoneFrame886")){
			String toUser = message.substring(message.indexOf("StoneFrame886")+10, message.indexOf("StoneFrame888"));
			message = message.substring(0, message.indexOf("StoneFrame886")) +"[私信]  "+ message.substring(message.indexOf("StoneFrame888")+12, message.length());
			ChatServerPool.sendMessage(ChatServerPool.getWebSocketByUser(toUser),message);//向所某用户发送消息
			ChatServerPool.sendMessage(conn, message);//同时向本人发送消息
		}else{
			ChatServerPool.sendMessage(message.toString());//向所有在线用户发送消息
		}
	}

	@Override
	public void onOpen(WebSocket conn, ClientHandshake arg1) {
		// TODO Auto-generated method stub
		System.out.println("即时通讯===触发连接事件===" + conn.getRemoteSocketAddress().getAddress().getHostAddress());
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		System.out.println("即时通讯===启动===");
	}
	
	/**
	 * 加入用户
	 */
	public void userJoin(String user,WebSocket conn){
		JSONObject result=new JSONObject();
		try {
			result.put("type", "user_join");
			result.put("user", user);
			ChatServerPool.sendMessage(result.toString());
			String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"上线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
			ChatServerPool.sendMessage(joinMsg);						//向所有在线用户推送当前用户上线的消息
			result = new JSONObject();
			result.put("type", "get_online_user");
			ChatServerPool.addUser(conn, user);
			result.put("list", ChatServerPool.getUser());
			ChatServerPool.sendMessage(conn, result.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 移除用户
	 */
	public void userLeave(WebSocket conn){
		String user=ChatServerPool.getUserByKey(conn);
		boolean b=ChatServerPool.removeUser(conn);
		if(b){
			JSONObject result=new JSONObject();
			try {
				result.put("type", "user_leave");
				result.put("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
				ChatServerPool.sendMessage(result.toString());			//把当前用户从所有在线用户列表中删除
				String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"下线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
				ChatServerPool.sendMessage(joinMsg);					//向在线用户发送当前用户退出的消息
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main( String[] args ) throws InterruptedException , IOException {
		WebSocketImpl.DEBUG = false;
		int port = 8887; //端口
		ChatServer s = new ChatServer(port);
		s.start();
		//System.out.println( "服务器的端口" + s.getPort() );
	}

}
